package com.advert.system.util;

import com.alibaba.fastjson2.JSONObject;
import com.advert.system.util.WXPayConstants.SignType;
import okhttp3.HttpUrl;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;


public class WXPayUtil {
    private static final Logger log = LoggerFactory.getLogger(WXPayUtil.class);
    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setExpandEntityReferences(false);
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }


    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key, SignType.MD5);
    }

    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名类型
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put(WXPayConstants.FIELD_SIGN, sign);
        return mapToXml(data);
    }


    /**
     * 判断签名是否正确
     *
     * @param xmlStr XML格式数据
     * @param key API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = xmlToMap(xmlStr);
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, SignType.MD5);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key, signType).equals(sign);
    }


    public static String generateSignature(final JSONObject json, String key) {
        Map<String, String> data = JsonUtil.fromJson(json.toJSONString(),Map.class);
        try {
            return generateSignature(data, key, SignType.MD5);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, SignType.MD5);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()+"").append("&");
        }
        sb.append("key=").append(key);
        log.info("sb====" + sb.toString());
        if (SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }


//    public static String getWXCert(JSONArray data) {
//        //敏感信息证书生成所需参数
//        String encryptCertificate = JSONObject.parseObject(
//                JSONObject.toJSONString(data.get(0))).getString("encrypt_certificate");
//        String nonce = JSONObject.parseObject(
//                encryptCertificate).getString("nonce");
//        String associatedData = JSONObject.parseObject(
//                encryptCertificate).getString("associated_data");
//        //要被解密的证书字符串
//        String cipherText = JSONObject.parseObject(
//                encryptCertificate).getString("ciphertext");
//        String wechatpayCert = "";
//        try {
//
//            wechatpayCert = aesgcmDecrypt(associatedData, nonce, cipherText);
//        } catch (Exception e) {
//            return wechatpayCert;
//        }
//        return wechatpayCert;
//    }
//
//    private static final String ALGORITHM = "AES/GCM/NoPadding";
//    private static final int TAG_LENGTH_BIT = 128;
//    // APIv3密钥
//    private static final String AES_KEY = "kseptonzhangjun1103jbvvvczkmklxb";
//
//    public static String aesgcmDecrypt(String aad, String iv, String cipherText){
//        try {
//            final Cipher cipher = Cipher.getInstance(ALGORITHM, "SunJCE");
//            SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES");
//            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, iv.getBytes());
//            cipher.init(Cipher.DECRYPT_MODE, key, spec);
//            cipher.updateAAD(aad.getBytes());
//            return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "fail";
//        }
//    }


    /**
     * 日志
     * @return
     */
    public static Logger getLogger() {
        Logger logger = LoggerFactory.getLogger("wxpay java sdk");
        return logger;
    }

    /**
     * 获取当前时间戳，单位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }

    /**
     * 获取当前时间戳，单位毫秒
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }

    /**
     * 生成 uuid， 即用来标识一笔单，也用做 nonce_str
     * @return
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    public static String  getAuthorization(String mchid,String seialNo,String pem,String method, HttpUrl url, String body) throws Exception {
        String nonceStr = generateUUID();
        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage(method, url, timestamp, nonceStr, body);
        String signature = sign(pem,message.getBytes("utf-8"));
        return "mchid=\"" + mchid + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "signature=\"" + signature + "\","
                + "timestamp=\""+timestamp+"\","
                + "serial_no=\"" + seialNo + "\"";
    }
    public static String sign(String pem,byte[] message) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(getPrivateKey(pem));
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }
    public static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();

        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }

    private static final String ALGORITHM = "AES/GCM/NoPadding";
    private static final int TAG_LENGTH_BIT = 128;

    public static String aesgcmDecrypt(String aad, String iv, String cipherText,String api3Key){
        try {
            final Cipher cipher = Cipher.getInstance(ALGORITHM, "SunJCE");
            SecretKeySpec key = new SecretKeySpec(api3Key.getBytes(), "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(aad.getBytes());
            return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

     /* 获取私钥。
     *
     * @param filename 私钥文件路径  (required)
     * @return 私钥对象
     */
    public static PrivateKey getPrivateKey(String content) throws IOException {
        try {
            String privateKey=content.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replaceAll("\\s+","");

            byte[] base64 = com.advert.common.utils.sign.Base64.decodeByte(privateKey.replaceAll("-----BEGINCERTIFICATE-----","").replaceAll("-----ENDCERTIFICATE-----",""));
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(base64));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            throw new RuntimeException("无效的密钥格式");
        }
    }


    public static boolean WxPointToken (String wechatpayNonce,String wechatpayTimestamp,String body,String cert,String signature) throws Exception {
        String sign = wechatpayTimestamp + "\n"
                + wechatpayNonce + "\n"
                + body + "\n";
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate x509Cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert.getBytes("utf-8")));
        x509Cert.checkValidity();
        return verify(sign,signature,x509Cert);
    }

    /**
     * 验签
     * @param srcData
     * @param signedData
     * @return
     */
    public static boolean verify(String srcData, String signedData, Certificate certificate){
        if(srcData==null || signedData==null ){
            return false;
        }
        try {
//            PublicKey publicKey = getPublicKey(publicKeyPath);
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initVerify(certificate.getPublicKey());
            sign.update(srcData.getBytes("utf-8"));
            return sign.verify(Base64.getDecoder().decode(signedData));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getRequestXml(SortedMap<String, String> params) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = params.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append("<" + k + ">" + v + "</" + k + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }


//    public static String uploadMediaV3(String filePath,String mchid,String seialNo,String pem,String apiV3Key)
//    {
//        String result = "";
//        try {
//            CloseableHttpClient httpClient;
//            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(pem);
//            //使用自动更新的签名验证器，不需要传入证书
//            Verifier verifier = new AutoUpdateCertificatesVerifier(
//                    new WechatPay2Credentials(mchid, new PrivateKeySigner(seialNo, merchantPrivateKey)),
//                    apiV3Key.getBytes(StandardCharsets.UTF_8));
//            httpClient = WechatPayHttpClientBuilder.create()
//                    .withMerchant(mchid, seialNo, merchantPrivateKey)
//                    .withValidator(new WechatPay2Validator(verifier))
//                    .build();
//            URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
//            File file = new File(filePath);
//            try (FileInputStream fileIs = new FileInputStream(file)) {
//                String sha256 = DigestUtils.sha256Hex(fileIs);
//                try (InputStream is = new FileInputStream(file)) {
//                    WechatPayUploadHttpPost request = new WechatPayUploadHttpPost.Builder(uri)
//                            .withImage(file.getName(), sha256, is)
//                            .build();
//                    try (CloseableHttpResponse response = httpClient.execute(request)) {
//                        HttpEntity entity = response.getEntity();
//                        String s = EntityUtils.toString(entity);
//                        result = s;
//                        System.out.println(s);
//                    }
//                }
//            }
//        }
//        catch(Exception e)
//        {
//            e.printStackTrace();
//        }
//        return result;
//    }


    public static String getFileSha256Hex(String filePath)
    {
        String result = "";
        try {
            File file = new File(filePath);
            String filename = file.getName();//文件名
            String fileSha256 = DigestUtils.sha256Hex(new FileInputStream(file));//文件sha256值
            result = fileSha256;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    public static String uploadMediaV3Ex(String mchid,String seialNo,String pem,String filePath){
        String result = "";
        try {

            // 换行符
            String LINE_END ="\r\n";
            String PREFIX ="--";
            // 定义数据分隔线
            String BOUNDARY ="";
            String nonce_str = generateUUID();
            //时间戳
            String timestamp = Long.toString(System.currentTimeMillis()/1000);


            File file =new File(filePath);
            String filename = file.getName();//文件名
            String fileSha256 = DigestUtils.sha256Hex(new FileInputStream(file));//文件sha256值

            //拼签名串
            StringBuffer sb =new StringBuffer();
            sb.append("POST").append("\n");
            sb.append("/v3/merchant/media/upload").append("\n");
            sb.append(timestamp).append("\n");
            sb.append(nonce_str).append("\n");
            sb.append("{\"filename\":\""+filename+"\",\"sha256\":\""+fileSha256+"\"}").append("\n");
            System.out.println("签名原串:"+sb.toString());

            //计算签名
            String sign =sign(pem,sb.toString().getBytes("utf-8"));
            System.out.println("签名sign值:"+sign);

            //拼装http头的Authorization内容
            String authorization ="WECHATPAY2-SHA256-RSA2048 mchid=\""+mchid+"\",nonce_str=\""+nonce_str+"\",signature=\""+sign+"\",timestamp=\""+timestamp+"\",serial_no=\""+seialNo+"\"";
            System.out.println("authorization值:"+authorization);

            //接口URL
            URL url =new URL("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("Charsert","UTF-8");
            conn.setRequestProperty("Accept","application/json");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("Authorization", authorization);

            DataOutputStream dos =new DataOutputStream(conn.getOutputStream());

            //拼装请求内容第一部分
            StringBuilder strSb =new StringBuilder();
            strSb.append(PREFIX).append(BOUNDARY).append(LINE_END)
                    .append("Content-Disposition: form-data; name=\"meta\";" + LINE_END)
                    .append("Content-Type: application/json; " + LINE_END)
                    .append(LINE_END)// 空行
                    .append("{\"filename\":\""+filename+"\",\"sha256\":\""+fileSha256+"\"}")
                    .append(LINE_END);
            dos.write(strSb.toString().getBytes());

            dos.flush();

            //拼装请求内容第二部分
            StringBuilder fileSbStart =new StringBuilder();
            fileSbStart.append(PREFIX).append(BOUNDARY).append(LINE_END)
                    .append("Content-Disposition: form-data; name=\"file\"; filename=\""+ filename+"\";" + LINE_END)
                    .append("Content-Type: image/jpeg" + LINE_END)
                    .append(LINE_END);// 空行
            dos.write(fileSbStart.toString().getBytes());

            dos.flush();

            //文件二进制内容
            InputStream is =new FileInputStream(file);
            byte[] buffer =new byte[1024];
            int len =0;
            while ((len = is.read(buffer)) != -1){
                dos.write(buffer,0,len);
            }
            is.close();

            //拼装请求内容结尾
            StringBuilder fileSbEnd =new StringBuilder();
            fileSbEnd.append(LINE_END)
                    .append(PREFIX).append(BOUNDARY).append(PREFIX)
                    .append(LINE_END);

            dos.write(fileSbEnd.toString().getBytes());

            dos.flush();
            dos.close();

            //接收返回
            //打印返回头信息
            System.out.println("接口返回头信息:");
            Map<String, List<String>> responseHeader = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : responseHeader.entrySet()) {
                System.out.println(entry.getKey()+":" + entry.getValue());
            }

            //打印返回内容
            int responseCode = conn.getResponseCode();
            String rescontent ="";
            result = conn.toString();
            if((responseCode+"").startsWith("2")){
                //成功
                rescontent =new String(InputStreamToByte(conn.getInputStream()));
                System.out.println("图片上传成功:"+rescontent);
            }else{
                //失败
                rescontent =new String(InputStreamToByte(conn.getErrorStream()));
                System.out.println("图片上传失败:"+rescontent);
            }

            //验证微信支付返回签名
            String Wtimestamp = responseHeader.get("Wechatpay-Timestamp").get(0);
            String Wnonce = responseHeader.get("Wechatpay-Nonce").get(0);
            String Wsign = responseHeader.get("Wechatpay-Signature").get(0);
            //拼装待签名串
            StringBuffer ss =new StringBuffer();
            ss.append(Wtimestamp).append("\n");
            ss.append(Wnonce).append("\n");
            ss.append(rescontent).append("\n");
            //验证签名


        }catch (Exception e) {
            System.out.println("发送POST请求异常！" + e);
            e.printStackTrace();
        }

        return result;
    }


    public static byte[] InputStreamToByte(InputStream is)  {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            return baos.toByteArray();
        }
        catch(Exception e) {
            return null;
        }
    }



}
